package cn.banyingli.banyinglilib.tools;

import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class DataTools {


    /**
     * 根据属性名获取属性值
     * */
    public static Object getFieldValueByName(String fieldName, Object o) {
        try {
            String firstLetter = fieldName.substring(0, 1).toUpperCase();
            String getter = "get" + firstLetter + fieldName.substring(1);
            Method method = o.getClass().getMethod(getter, new Class[]{});
            Object value = method.invoke(o, new Object[]{});
            return value;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * java利用反射机制获取list中的某个字段并以list形式返回
     * @param list
     * @param fieldName
     * @param <T>
     * @return
     * @throws Exception
     */
    public static<T> List<Object> listToList(Collection<T> list, String fieldName)  {
        List<Object> ret = new ArrayList();
        try{
            List<String>getStrs=null;
            List<Method> getMethods=new ArrayList<Method>();
            for(T t:list){
                if(getStrs==null){
                    getStrs = new ArrayList<String>();
                    for(String s:fieldName.split("\\.")){
                        getStrs.add("get"+s.substring(0,1).toUpperCase()+s.substring(1));
                    }
                }
                Object value = t;
                for(int i=0;i<getStrs.size();i++){

                    if(getMethods==null || getMethods.size()<=i ||getMethods.get(i)==null){
                        getMethods.add(value.getClass().getDeclaredMethod(getStrs.get(i)));
                    }
                    value=getMethods.get(i).invoke(value);
                }
                ret.add(value);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return ret;
    }


}
